package cn.fastpay.core.util;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    public static final String RSA_ALGORITHM = "RSA";

    /**
     * 从证书文件中得到公钥
     *
     * @throws Exception 证书解析失败
     */
    public static RSAPublicKey getPublicKey(String keyFileName) {
        try {
            Resource resource = new ClassPathResource(keyFileName);
            String publicKeyStr = loadKey(resource.getInputStream());
            KeyFactory kf = KeyFactory.getInstance(RSA_ALGORITHM);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr));
            return (RSAPublicKey) kf.generatePublic(x509EncodedKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析公钥证书出错：[" + e.getMessage() + "]");
        }
    }

    public static String loadKey(InputStream in) throws Exception {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
            String readLine;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                if (readLine.charAt(0) != '-') {
                    sb.append(readLine);
                }
            }
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("证书解析错误出错", e);
        } catch (NullPointerException e) {
            throw new Exception("证书文件没有找到", e);
        }
    }
}
